/**
 * 用户授权登录
 */

// pages/index/auth/auth.js
import CommonPage from "../../common/CommonPage.js"
const app = getApp()
const api = require("../../api/http.js")
const config = require("../../../config.js")
const com = require("../../../utils/util.js")

class AuthPage extends CommonPage {
  constructor(...args) {
    super(...args)
    this.data = {
      //判断小程序的API，回调，参数，组件等是否在当前版本可用。
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      //无效
      canCompUse: wx.canIUse('selectComponent')
    }
  }

  getOpenId = function() {
    var loginCode = null
    wx.login({
      success: res => {
        if (res.code) {
          var param = {
            code: res.code
          }
          api.post(config.userInfoUrl, param).then(re => {
            console.debug("getOpneId:\n", re)
            var user = re.userInfo
            if (user) {
              app.globalData.openId = user.openId
              app.globalData.unionId = user.unionId
              app.globalData.userInfo['openId'] = user.openId
              app.globalData.userInfo['unionId'] = user.unionId
              wx.setStorageSync('userInfo', app.globalData.userInfo)
              app.globalData.hasUserInfo = true
              com.registerUser(app.globalData.userInfo)
            } else {
              console.error("获取用户信息失败！")
            }
          })
        } else {
          console.error("Login for code failed!")
          wx.showToast({
            title: '登录信息获取失败！',
            icon: 'none'
          })
        }
      }
    })
  }
  onLoad = function (arg) {
    /**
     * 测试
     // arg.openId = 'haha'
     // arg.name = '蔡爷'
     // arg.step = 1024
     */
    if (arg.openId) {
      console.debug("邀请好友数据：", arg) 
      wx.setStorageSync("invitation", arg)
    }
    var that = this;
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              //用户已经授权过
              // console.log("GetUserInfo-res:", res)
              // var encry = res.encryptedData
              // var iv = res.iv
              app.globalData.userInfo = res.userInfo
              that.getOpenId()
              setTimeout(() => {
                wx.switchTab({
                  url: '../index'
                })
              }, 150)
            }
          });
        } else {
          console.error("未授权用户信息")
        }
      },
      fail: () => {
        console.error("获取授权信息失败")
      }
    })
  }
  bindGetUserInfo = function (e) {
    var dat = e.detail
    console.log("首次授权登录：", dat)
    if (dat.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      var encry = dat.encryptedData
      var iv = dat.iv
      app.globalData.userInfo = dat.userInfo
      this.getOpenId()
      //授权成功后，跳转进入小程序首页
      app.globalData.authorized = true
      setTimeout(() => {
        wx.switchTab({
          url: '../index'
        })
      }, 150)
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  }
}
Page(new AuthPage({clazzName: "AuthPage"}))